/*******************************************************************************
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package org.desktop.web.client;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.desktop.web.client.custom.widget.DesktopFolder;
import org.desktop.web.client.custom.widget.DesktopFolder.Icon;
import org.desktop.web.client.custom.widget.LoginWidget;
import org.desktop.web.client.images.Resources;
import org.desktop.web.client.login.window.ChangePasswordWidget;
import org.desktop.web.client.project.window.ProjectWindow;
import org.desktop.web.client.role.window.RolesWindow;
import org.desktop.web.client.timesheet.window.TimesheetWindow;
import org.desktop.web.client.users.window.UsersWindow;
import org.desktop.web.shared.constant.Token;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.cell.core.client.ButtonCell.IconAlign;
import com.sencha.gxt.core.client.resources.ThemeStyles;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer;
import com.sencha.gxt.widget.core.client.container.BorderLayoutContainer.BorderLayoutData;
import com.sencha.gxt.widget.core.client.container.CardLayoutContainer;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.NorthSouthContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.Viewport;
import com.sencha.gxt.widget.core.client.info.Info;
import com.sencha.gxt.widget.core.client.menu.CheckMenuItem;
import com.sencha.gxt.widget.core.client.menu.DateMenu;
import com.sencha.gxt.widget.core.client.menu.HeaderMenuItem;
import com.sencha.gxt.widget.core.client.menu.Item;
import com.sencha.gxt.widget.core.client.menu.Menu;
import com.sencha.gxt.widget.core.client.menu.MenuBar;
import com.sencha.gxt.widget.core.client.menu.MenuBarItem;
import com.sencha.gxt.widget.core.client.menu.MenuItem;
import com.sencha.gxt.widget.core.client.menu.SeparatorMenuItem;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class DesktopViewer implements IsWidget, EntryPoint {
	private ContentPanel panel;

	public static String token = "";

	private static Map<String, DesktopFolder> foldersMap = new HashMap<String, DesktopFolder>();

	static {
		// foldersMap.put("Timesheet", new
		// DesktopFolder("Timesheet",Icon.TIMESHEET,TimesheetWindow));
		// foldersMap.put("Progetti", new
		// DesktopFolder("Progetti",Icon.PROJECTS));
		// foldersMap.put("Ruoli", new DesktopFolder("Ruoli",Icon.ROLES));
		// foldersMap.put("Utenti", new DesktopFolder("Timesheet",Icon.USERS));
		// foldersMap.put("Utenti", new DesktopFolder("Timesheet",Icon.USERS));

	}

	private Viewport viewport;

	public Viewport getViewport() {
		return viewport;
	}

	public void onModuleLoad() {
		viewport = new Viewport();
		// com.google.gwt.user.client.Window.alert();
		token = Cookies.getCookie("token");
		String aSpecificToken = com.google.gwt.user.client.Window.Location.getParameter("tkn");
		if(aSpecificToken!=null && !aSpecificToken.trim().equals("")){
			ChangePasswordWidget cpw = new ChangePasswordWidget(this,Token.RECOVER);
			
			return;

		}
		if (token == null || token.equals("undefined")) {
			LoginWidget login = new LoginWidget(this);
			
//			BorderLayoutContainer blc = new BorderLayoutContainer();
//			blc.getElement().getStyle().setBackgroundColor("#DFE8F6");
//			blc.setBorders(false);
//			BorderLayoutData bld = new BorderLayoutData();
//			bld.setSize(0.3);
//			bld.setMargins(new Margins(0));
//			BorderLayoutData eastWest = new BorderLayoutData();
//			eastWest.setSize(0.35);
//			eastWest.setMargins(new Margins(0));
//			blc.setCenterWidget(login, bld);
//			blc.setEastWidget(east, eastWest);
//			blc.setWestWidget(west, eastWest);
//			blc.setNorthWidget(north, eastWest);
//			blc.setSouthWidget(south, eastWest);
//			viewport.add(blc);

		} else {
			enter();
			RootPanel rootPanel = RootPanel.get();
			rootPanel.add(viewport);
		}


	}

	public VerticalLayoutContainer createEmptyPanel() {
		VerticalLayoutContainer north = new VerticalLayoutContainer();
		// north.setHeaderVisible(false);
		// north.setBodyBorder(false);
		north.setVisible(false);
		// north.getElement().getStyle().setBorderStyle(BorderStyle.NONE);
		// north.setBodyStyle("background-color: #DFE8F6 !important;");
		return north;
	}

	/**
	 * Motodo che visualizza il desktop.
	 */
	public void enter() {
		// TODO Auto-generated method stub

		Menu menu = new Menu();

		MenuItem background = new MenuItem("Sfondo Scrivania");
		menu.add(background);
		menu.addSelectionHandler(new SelectionHandler<Item>() {

			@Override
			public void onSelection(SelectionEvent<Item> event) {
				// cambia lo sfondo della scrivania

			}

		});

		viewport.setContextMenu(menu);
		VerticalLayoutContainer vlc = new VerticalLayoutContainer();
		// prelevo dai cookie le info di sessione sulle funzioni abilitate!
		String functionsString = Cookies.getCookie("functions");
		JSONValue jsonValue = JSONParser.parseStrict(functionsString);
		JSONArray jsonArray = jsonValue.isArray();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject obj = jsonArray.get(i).isObject();
			// com.google.gwt.user.client.Window.alert(obj.toString());

			JSONValue value = obj.get("descFunction");
			// com.google.gwt.user.client.Window.alert(value.toString());
			DesktopFolder df = foldersMap.get(value.isString().stringValue());
			// vlc.add(df);

		}
		DesktopFolder timesheet = new DesktopFolder("Timesheet",
				Icon.TIMESHEET, (Window) GWT.create(TimesheetWindow.class));
		DesktopFolder folder = new DesktopFolder("Progetti", Icon.PROJECTS,
				 (Window) GWT.create(ProjectWindow.class));
		DesktopFolder roles = new DesktopFolder("Ruoli", Icon.ROLES,
				 (Window) GWT.create(RolesWindow.class));
		DesktopFolder users = new DesktopFolder("Users", Icon.USERS,
				 (Window) GWT.create(UsersWindow.class));
		vlc.add(timesheet);
		vlc.add(folder);
		vlc.add(users);
		vlc.add(roles);
		viewport.add(vlc);
		// viewport.add(asWidget());

	}

	@Override
	public Widget asWidget() {
		if (panel == null) {
			SelectionHandler<Item> handler = new SelectionHandler<Item>() {
				@Override
				public void onSelection(SelectionEvent<Item> event) {
					if (event.getSelectedItem() instanceof MenuItem) {
						MenuItem item = (MenuItem) event.getSelectedItem();
						Info.display("Action",
								"You selected the " + item.getText());
					}
				}
			};

			Menu menu = new Menu();
			menu.addSelectionHandler(handler);

			MenuItem item1 = new MenuItem("New");
			menu.add(item1);

			MenuItem item2 = new MenuItem("Open File");
			menu.add(item2);

			Menu sub = new Menu();
			sub.addSelectionHandler(handler);

			sub.add(new MenuItem("readme.txt"));
			sub.add(new MenuItem("helloworld.txt"));
			item2.setSubMenu(sub);

			MenuBar bar = new MenuBar();
			bar.addStyleName(ThemeStyles.get().style().borderBottom());

			bar.add(new MenuBarItem("File", menu));

			Menu sub2 = new Menu();
			sub2.addSelectionHandler(handler);
			sub2.add(new MenuItem("Cut"));
			sub2.add(new MenuItem("Copy"));

			MenuBarItem edit = new MenuBarItem("Edit", sub2);
			bar.add(edit);

			sub = new Menu();
			sub.addSelectionHandler(handler);
			sub.add(new MenuItem("Search"));
			sub.add(new MenuItem("File"));
			sub.add(new MenuItem("Java"));

			MenuBarItem item3 = new MenuBarItem("Search", sub);
			bar.add(item3);

			menu = new Menu();
			menu.addSelectionHandler(handler);

			CheckMenuItem menuItem = new CheckMenuItem("I Like Cats");
			menuItem.setChecked(true);
			menu.add(menuItem);

			menuItem = new CheckMenuItem("I Like Dogs");
			menu.add(menuItem);

			menu.add(new SeparatorMenuItem());

			MenuItem radios = new MenuItem("Radio Options");
			menu.add(radios);

			Menu radioMenu = new Menu();
			radioMenu.addSelectionHandler(handler);
			radioMenu.add(new HeaderMenuItem("Built-in GXT Themes"));
			CheckMenuItem r = new CheckMenuItem("Blue Theme");
			r.setGroup("radios");
			r.setChecked(true);
			radioMenu.add(r);
			r = new CheckMenuItem("Gray Theme");
			r.setGroup("radios");
			radioMenu.add(r);
			r = new CheckMenuItem("Neptune Theme");
			r.setGroup("radios");
			radioMenu.add(r);
			radios.setSubMenu(radioMenu);

			MenuItem date = new MenuItem("Choose a Date");
			date.setIcon(Resources.IMAGES.folder());
			menu.add(date);

			final DateMenu dateMenu = new DateMenu();
			dateMenu.getDatePicker().addValueChangeHandler(
					new ValueChangeHandler<Date>() {

						@Override
						public void onValueChange(ValueChangeEvent<Date> event) {
							Date d = event.getValue();
							DateTimeFormat f = DateTimeFormat
									.getFormat(PredefinedFormat.DATE_SHORT);
							Info.display("Value Changed",
									"You selected " + f.format(d));
							dateMenu.hide(true);
						}
					});
			date.setSubMenu(dateMenu);

			MenuBarItem item4 = new MenuBarItem("Foo", menu);
			bar.add(item4);

			panel = new ContentPanel();
			panel.setHeaderVisible(false);
			panel.setHeadingText("MenuBar Example");
			panel.setPixelSize(400, 300);
			// panel.setLayoutData(new MarginData(10));

			CardLayoutContainer clc = new CardLayoutContainer();

			TextButton b = new TextButton();
			b.setIcon(Resources.IMAGES.folder());
			b.setIconAlign(IconAlign.TOP);
			b.setText("Prova");
			b.setPixelSize(30, 30);
			b.setBorders(false);
			b.setAllowTextSelection(true);

			VerticalLayoutContainer vertical = new VerticalLayoutContainer();
			vertical.add(b);
			vertical.setLayoutData(new MarginData(10));
			clc.add(vertical);

			NorthSouthContainer comp = new NorthSouthContainer();
			comp.setNorthWidget(bar);
			comp.setSouthWidget(clc);
			panel.add(comp);

		}

		return panel;
	}
}
